import { useState, useEffect, useCallback } from 'react'
import Taro, { useRouter } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import { AtButton, AtIcon } from 'taro-ui'

import classnames from 'classnames'
import dayjs from 'dayjs'
import isToday from 'dayjs/plugin/isToday'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'


import './index.scss'
import { customScheduleTime } from '@/utils'
import { dayTextFormat } from '@/utils/formatter'

// 添加插件
dayjs.extend(isToday) // 是否是今天
dayjs.extend(isSameOrBefore) // 相同或之前

const aaa = [
  {
    key: '2021-07-03',
    selected: [
      '17:00-17:30'
    ]
  },
  {
    key: '2021-07-04',
    selected: [
      '09:00-09:30'
    ]
  }
]

// 一整天的时间数据
const scheduleDate = customScheduleTime() || []

const Schedule = () => {
  const [scrollIntoView, setscrollIntoView] = useState('')
  const [dateData, setDateData] = useState([])
  const [startDate, setstartDate] = useState(null)
  const [endDate, setendDate] = useState(null)

  // 选中的Tab日期
  const [selectTabDate, setSelectTabDate] = useState(dayjs().format('YYYY-MM-DD'))

  // 选中的要预约的日期
  const [selectDate, setSelectDate] = useState([])
  
  // 已预约的时间数据
  const [selectedScheduleDate, setSelectScheduleDate] = useState([])
  
  const [isNotClick, setIsNotClick] = useState(true)

  // 切换日期
  const handleChangeTab = key => {
    if (key === selectTabDate) return false
    setSelectTabDate(key)
  }

  // 点击选择预约时间
  const handleSelect = ({ key, end }) => {
    if (isOutDate(end)) return false
    if (selectedScheduleDate.includes(key)) return false
    setSelectDate(prevState => {
      if (prevState.includes(key)) {
        return prevState.filter(item => item !== key) || []
      }
      return [...prevState, key]
    })
  }

  // 打开日历
  const openCalendar = () => {
    Taro.navigateTo({
      url: `/pages/calendar/index?start=${startDate}&end=${endDate}&select=${selectTabDate}`
    })
  }

  // 判断是否过期时间
  const isOutDate = end => {
    const date = dayjs(`${selectTabDate} ${end}`)
    return dayjs().isAfter(date, 'minute')
  }

  // 监听路由的参数
  const router = useRouter()
  useEffect(() => {
    const { params } = router

    // 最后期限没有超过当前时间
    if (dayjs().isSameOrBefore(dayjs(params.end), 'day')) {
      console.log('最后期限没有超过当前时间')
      const start = dayjs().isSameOrBefore(dayjs(params.start), 'day') ? dayjs(params.start) : dayjs().startOf('day')
      // const startDate = dayjs(params.start);
      const end = dayjs(params.end)
      const duration = Math.abs(end.diff(start, 'day'))

      console.log(5555, duration)
      setstartDate(start)
      setendDate(end)
      setDateData(() => {
        return Array.from({ length: duration + 1 }, (_, index) => {
          const date = dayjs().add(index, 'day')
          return {
            key: date.format('YYYY-MM-DD'),
            value: date.isToday() ? '今天' : dayTextFormat(date)
          }
        })
      })
    } else {
      console.log('最后期限超过当前时间')
      setDateData([])
      setstartDate('')
      setendDate('')
    }
    return () => {}
  }, [router])

  useEffect(() => {
    // 监听一个事件，接受参数
    Taro.eventCenter.on('scrollIntoView', (arg) => {
      Taro.nextTick(() => {
        setSelectTabDate(arg)
      })
    })
    return () => {
      Taro.eventCenter.off('scrollIntoView')
    }
  }, [])

  // 获取当前的日期下的预约情况
  const getScheduleDateData = useCallback(
    data => {
      const result = data.filter(item => item.key === selectTabDate) || []
      return result[0]?.selected || []
    },
    [selectTabDate],
  )

  useEffect(() => {
    const result = aaa.length ? getScheduleDateData(aaa) : []
    setSelectScheduleDate(result)
    return () => {}
  }, [getScheduleDateData])

  // 切换Tab日期 （重置选中的日期）
  useEffect(() => {
    setSelectDate([])
    setscrollIntoView(`tt_${selectTabDate}`)
    return () => {}
  }, [selectTabDate])

  // 是否能点击提交预约
  useEffect(() => {
    setIsNotClick(selectDate.length <= 0)
    return () => {}
  }, [selectDate])

  return (
    <View className='schedule-component'>
      <View className='schedule-header'>
        <ScrollView
          className='scrollviews'
          scrollX
          scrollWithAnimation
          scrollIntoView={scrollIntoView}
        >
          {
            dateData.map(item => (
              <View
                id={`tt_${item.key}`}
                key={item.key}
                className={classnames('scrollview', item.key === selectTabDate ? 'active' : '')}
                onClick={() => handleChangeTab(item.key)}
              >
                <View className='date-wrap'>
                  <View className='date-name'>
                    {item.value}
                  </View>
                  <View className='date-text'>
                    {item.key}
                  </View>
                </View>
              </View>
            ))
          }
        </ScrollView>
        {
          dateData.length > 0 && (
            <View className='calendar-btn'>
              <AtIcon
                value='calendar'
                size='30'
                color='#6190e8'
                onClick={openCalendar}
              />
            </View>
          )
        }
      </View>

      <View className='schedule-box'>
        {
          scheduleDate.length > 0 && (
            <View className='schedule-list'>
              {
                scheduleDate.map(item => (
                  <View
                    key={item.key}
                    className={classnames(
                      'schedule-item',
                      isOutDate(item.end) ? 'disabled' : selectedScheduleDate.includes(item.key) ? 'selected' : '',
                      selectDate.includes(item.key) ? 'active' : ''
                    )}
                    onClick={() => handleSelect(item)}
                  >
                    <View className='schedule-info'>
                      {item.start}-{item.end}
                    </View>
                  </View>
                ))
              }
            </View>
          )
        }
      </View>

      <View className='remain-time'>
        剩余预约时长<Text className='time'>4.5小时</Text>
      </View>

      <View className='legend-list'>
        <View className='legend-item'>
          <View className='legend-icon disabled' />
          <View className='legend-text'>
            不可预约
          </View>
        </View>
        <View className='legend-item'>
          <View className='legend-icon' />
          <View className='legend-text'>
            可预约
          </View>
        </View>
        <View className='legend-item'>
          <View className='legend-icon selected' />
          <View className='legend-text'>
            已订阅
          </View>
        </View>
        <View className='legend-item'>
          <View className='legend-icon active' />
          <View className='legend-text'>
            我的预约
          </View>
        </View>
      </View>
      
      <View className='btns'>
        <AtButton type='primary' disabled={isNotClick}>
          确定预约
        </AtButton>
      </View>
    </View>
  )
}

export default Schedule
